<?

require(dirname(__FILE__).'/_base/BaseFile.php');

class File extends BaseFile{
    
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }
    
    public function rules() {
        return array(
            array('user_ip, md5, name, code, path, size, mime', 'required'),
            array('time_create, user_id, size', 'numerical', 'integerOnly'=>true),
            array('user_ip, mime', 'length', 'max'=>60),
            array('md5', 'length', 'max'=>32),
            array('name, code, path', 'length', 'max'=>255),
            array('id, time_create, user_ip, user_id, md5, name, code, path, size, mime', 'safe', 'on'=>'search'),
        );
    }
    
    public function attributeLabels() {
        return array(
            'id' => Yii::t('app', 'ID'),
            'time_create' => Yii::t('app', 'Дата создания'),
            'user_ip' => Yii::t('app', 'IP пользователя'),
            'user_id' => Yii::t('app', 'Пользователь'),
            'md5' => Yii::t('app', 'md5'),
            'name' => Yii::t('app', 'Название'),
            'code' => Yii::t('app', 'Код'),
            'path' => Yii::t('app', 'Путь'),
            'size' => Yii::t('app', 'Размер'),
            'mime' => Yii::t('app', 'Mime тип'),
        );
    }
    
    /**
     * Метод сохраняет загруженный файл на сервере и в БД.
     * @param array $FILE - массив из $_FILES
     * @return int
     */
    public function push($FILE, $path='/upload'){
        
        $F = false;
        
        if($FILE['error'] == UPLOAD_ERR_OK){
            
            $md5hash = md5_file($FILE['tmp_name']);
            
            $F = self::model()->findByAttributes(array( 'md5' => $md5hash ));
            
            $needMakeFile = false;
            
            if(!$F){
                $needMakeFile = true;
                $F = new self;
            }elseif(!file_exists($_SERVER['DOCUMENT_ROOT'].$F->path.'/'.$F->code)){
                $needMakeFile = true;
            }
            
            if($needMakeFile){
                $hash = md5(time().rand().$FILE['tmp_name'].rand());
                
                $path = $path.'/'.substr($hash, 0, 2).'/'.substr($hash, 2, 2).'/'.substr($hash, 4, 2);
                
                $expath = explode('/', $path); $_expath = '';
                foreach($expath as $p){
                    $__f = $_SERVER['DOCUMENT_ROOT'].$_expath.'/'.$p;
                    if(!file_exists($__f)){
                        mkdir($__f); chmod($__f, 0777);
                    }
                    $_expath .= '/'.$p;
                }
                
                $ext = CFileHelper::getExtension($FILE['name']);
                $mime = CFileHelper::getMimeType($FILE['name']);
                
                $__path = $_SERVER['DOCUMENT_ROOT'].$path.'/'.$hash.'.'.$ext;
                move_uploaded_file($FILE['tmp_name'], $__path);
                chmod($__path, 0777);
                
                $F->time_create = time();
                $F->user_ip = CHttpRequest::getUserHostAddress();
                $F->user_id = Yii::app()->user->id;
                $F->md5 = $md5hash;
                $F->name = $FILE['name'];
                $F->code = $hash.'.'.$ext;
                $F->path = $path;
                $F->size = $FILE['size'];
                $F->mime = $mime;
                $F->save();
            }
            
        }
        
        return $F;
        
    }
    
}
